package com.hrms.view;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.hrms.core.Constants;
import com.hrms.core.Constants.Transaction;
import com.hrms.core.EmailMsg;
import com.hrms.core.TemplateManager.Templates;
import com.hrms.core.Utils;
import com.hrms.domain.BusinessObjectImpl;
import com.hrms.domain.Employee;
import com.hrms.domain.Post;

public class DiscussionView extends TeamDashboardView {
	
	public static final String SELECTED_DATE = Post.TYPE+"_SelectedDate";
	
	private String userId = null;
	private Employee viewingUser = null;
	private Date selectedDate = null;
	
	@Override
	public void service(HttpServletRequest req, HttpServletResponse res) {
		super.service(req, res);
	}
	
	@Override
	protected void persistEvents() {
		log(getUserAction());
		if (StringUtils.isNotEmpty(getUserAction())) {

			try {

				if (Constants.Action.NEW.toString().equals(getUserAction())) {
					addAsAParameter("initials", getAccessor().getInitials());
					
						Post post = new Post(getParameterMap());			
						setWarnings( post.fireEvents(getUserAction(), getReq()) );
						
						log("isTeam "+isTeam());
						if(isTeam()){
							
							try{
								log("Team Alet is ON");
							
							 List<String> emailList = Employee.getMailListByTeam(viewingUser.getTeam());
							 
							 log("Team Size "+ emailList.size());
							 
							 for(String emailuid : emailList){
								 
								 if( (!emailuid.contains(userId)) && (!emailuid.contains(getAccessor().getUserId())) ){
							
									 log("Emailing to "+ emailuid);
									 
								 Map<String, Object> params = new HashMap<String, Object>();
									params.put("user", getAccessor().getName());
									params.put("appId", Constants.APP_ID);
									params.put("post", post.getMsg());
									
									EmailMsg email = new EmailMsg();
									email.getRecipients().add(emailuid);
									email.setSubject("Team Discussion : New Post");
									email.setTemplate(Templates.teamPost);
									email.setParams(params);
									email.send();
								 }
							 }
							 
							}catch(Exception ex){
								//ignore
								log.log(Level.WARNING, "Failed to Email Team Discussion Alerts", ex);
							}
							
						}else if(!isSuper()){
							 Map<String, Object> params = new HashMap<String, Object>();
							 	params.put("to", viewingUser.getName());
								params.put("user", getAccessor().getName());
								params.put("appId", Constants.APP_ID);
								params.put("post", post.getMsg());
								
								EmailMsg email = new EmailMsg();
								email.getRecipients().add(userId);
								email.setSubject(getAccessor().getName()+" posted on your Wall");
								email.setTemplate(Templates.wallPost);
								email.setParams(params);
								email.send();
						}
				}

			} catch (Exception e) {
				setWarnings( Transaction.Failed.getMsg() ); 
				log.log(Level.SEVERE, getWarnings(), e);
			}
			log(getWarnings());
			getReq().setAttribute("msg", getWarnings());
		}
	}

	@Override
	protected void initalize() {
		userId = getReqesutedUserId();
		
		if(!isSuper()){
			viewingUser = Employee.getByUserId(userId);
			//posts should be made through walls , override it to viewing userwall
			addAsAParameter("userId", viewingUser.getUserId());
		}else{
			viewingUser = getAccessor();
		}
		
		log(getMapValue(SELECTED_DATE));
		if(StringUtils.isNotEmpty(getMapValue(SELECTED_DATE))){
			selectedDate = Utils.safeParseDate(getMapValue(SELECTED_DATE));
		}
		
		checkForTeamUser();
		
	}

	public String getUserId() {
		return userId;
	}

	public Employee getViewingUser() {
		return viewingUser;
	}
	
	public Date getSelectedDate() {
		return selectedDate;
	}

	public List<Post> getUserPosts(){
		Integer paramCount = 0;
		StringBuilder sb = new StringBuilder("where userId == :a ");
		Object[] params  = new Object[2];  		
		params[paramCount++] = viewingUser.getUserId();
		
		if(selectedDate != null){
			sb.append(" && date >= :c ");
			params[paramCount++]=selectedDate;		
			sb.append("  order by date desc ");
			return BusinessObjectImpl.select(Post.class, sb.toString() , params);
			
		}else{
			sb.append("  order by date desc ");
			return BusinessObjectImpl.select(Post.class, 0, 20, sb.toString() , params);
		}
		
	}

}
